package com.moose.operator.web.service.impl.book;

import com.moose.operator.common.PageInfo;
import com.moose.operator.common.QueryWrapper;
import com.moose.operator.model.entity.HistoryBookCategory;
import com.moose.operator.model.param.SearchParam;
import com.moose.operator.web.service.HistoryBookCategoryService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.stereotype.Service;

/**
 * @author taohua
 */
@Service
public class HistoryBookCategoryServiceImpl implements HistoryBookCategoryService {

  @Resource
  private MongoTemplate mongoTemplate;

  @Override public PageInfo<HistoryBookCategory> getCategoryList(SearchParam searchParam) {

    Integer pageNum = searchParam.getPageNum();
    Integer pageSize = searchParam.getPageSize();
    Aggregation aggregation = Aggregation.newAggregation(
        Aggregation.project(
            "category_id", "category_name", "category_py", "description"),
        QueryWrapper.buildSkipOperation(pageNum, pageSize),
        QueryWrapper.buildLimitOperation(pageSize));

    AggregationResults<Document> aggregate =
        mongoTemplate.aggregate(aggregation, "history_book_category", Document.class);

    List<Document> mappedResults = aggregate.getMappedResults();

    List<HistoryBookCategory> historyBookCategoryList = mappedResults.stream().map(document -> {
      HistoryBookCategory historyBookCategory = new HistoryBookCategory();
      historyBookCategory.setCategoryId(document.getLong("category_id"));
      historyBookCategory.setCategoryName(document.getString("category_name"));
      historyBookCategory.setCategoryPy(document.getString("category_py"));
      historyBookCategory.setDescription(document.getString("description"));
      return historyBookCategory;
    }).collect(Collectors.toList());

    long totalSize = mongoTemplate.count(QueryWrapper.buildQuery(), HistoryBookCategory.class);
    PageInfo<HistoryBookCategory> pageInfo = new PageInfo<>();
    pageInfo.setList(historyBookCategoryList);
    pageInfo.setPageSize(pageSize);
    pageInfo.setTotalSize(totalSize);
    pageInfo.setPageNum(pageNum);

    return pageInfo;
  }
}
